package servlet;

import pojo.Dept;
import service.DeptService;
import service.impl.DeptServiceimpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet(urlPatterns = "/dept")
public class DeptServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        DeptService deptService = new DeptServiceimpl();
        String action = req.getParameter("action");
        req.setCharacterEncoding("UTF-8");
       if ("list2".equals(action)){
           String dname = req.getParameter("dname");


           Dept Condition = new Dept(dname);

           List<Dept> depts = deptService.findAll(Condition);
           // 把数据放到请求域中
           req.setAttribute("depts", depts);
           req.setAttribute("Condition", Condition);
           req.getRequestDispatcher("/list2.jsp").forward(req, resp);
       }
       else if("delete".equals(action)){
           String sid= req.getParameter("id");
           Integer id=Integer.parseInt(sid);
           int result = deptService.DeleteDeptById(id);
           if (result > 0) {
               // 重定向到查询所有用户的页面
               resp.sendRedirect("dept?action=list2");
           }else {}

       }
       else if("add".equals(action)){
           String dname = req.getParameter("dname");

           int result = deptService.addDept(new Dept(dname));
           if(result>0){
               resp.sendRedirect("dept?action=list2");
           }
           else {
               resp.sendRedirect("addDept.jsp");
           }
       }
       else if("update".equals(action)){
           String sid = req.getParameter("id");
           Integer id = Integer.parseInt(sid);
           // 拿到网页传递过来的用户名和密码
           String dname = req.getParameter("dname");


           int result = deptService.UpdateDept(new Dept(id,dname));
           if (result>0) {
               resp.sendRedirect("dept?action=list2");
           }
           else{
           }
       }
       else if("toUpdate".equals(action)){

           // 设置请求字符

           // 拿到网页传递过来的用户名和密码
           String sid = req.getParameter("id");

           Integer id = Integer.parseInt(sid);

           // 根据id查询用户信息
           Dept dept = deptService.findByid(id);

           // 将查询到的用户信息存储到作用域中
           req.setAttribute("dept", dept);
           req.getRequestDispatcher("UpdateDept.jsp").forward(req, resp);
       }
    }
}
